#coding=utf-8
'''
Created on 2017-6-13

@author: sandy
'''

from twisted.internet.protocol import ReconnectingClientFactory
from twisted.internet import reactor
import Const
import logging
import TBaseProtocol
import ManagerBuild
import ManagerParse
import RemoteManager

class ManagerFactory(ReconnectingClientFactory):
    def __init__(self):
        ReconnectingClientFactory.maxDelay = 5
    
    def buildProtocol(self, addr):
        logging.info(u"ManagerFactory buildProtocol!!!")
        self.resetDelay()
        return instance
    
    def startedConnecting(self, connector):
        logging.info(u"ManagerFactory startedConnecting!!!")
    
    def clientConnectionLost(self, connector, reason):
        logging.warn(u"ManagerFactory clientConnectionLost!!!")
        ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
        
    def clientConnectionFailed(self, connector, reason):
        logging.warn(u"ManagerFactory clientConnectionFailed!!!")
        ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)

class ManagerSrv(TBaseProtocol.TBaseProtocol):
                      
    def __init__(self):
        TBaseProtocol.TBaseProtocol.__init__(self)
    
    def start(self, ip, port):
        reactor.connectTCP(ip,port,ManagerFactory())
        
    def stop(self):
        pass
    
    def connectionMade(self):
        logging.info(u"Manager connectionMade()")
        TBaseProtocol.TBaseProtocol.reset(self)
        self.sendPacket(ManagerBuild.login(RemoteManager.instance.sid))
        
    def packetReceived(self, cmd, pkt):
        try:
            ManagerParse.parse(self, cmd, pkt)
        except Exception:
            logging.exception(u"LogServerParse.parse(), cmd=%d" % cmd)

instance = ManagerSrv()

if __name__ == '__main__':
    pass